package com.openthinks.joyniproject.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.openthinks.joyniproject.model.UserInfo;

public class LoginInterceptor extends HandlerInterceptorAdapter {

	/**
	 * 在DispatcherServlet完全处理完请求后被调用
	 */
	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}

	/**
	 * 在业务处理器处理请求执行完成后,生成视图之前执行的动作
	 */
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
	}

	/**
	 * 在业务处理之前调用
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object arg2) throws Exception {
		// 不过滤的uri,系统后期添加的不需过滤的action可在此列出
				String[] notInterceptor = new String[] { "login.json"};
				// 请求的uri
				String uri = request.getRequestURI();
				System.out.println(uri);
				
				// 是否过滤
				boolean doInterceptor = true;
				for (String s : notInterceptor) {
					if (uri.indexOf(s) != -1) {
						// 如果uri中包含不过滤的uri，则不进行过滤
						doInterceptor = false;
						break;
					}
				}
				
				if(doInterceptor){
					HttpSession session = request.getSession();
				
					//从session获取用户信息
					UserInfo userInfo = (UserInfo)session.getAttribute("userInfo");
					
					if (null == userInfo){
						if (request.getHeader("x-requested-with") != null
								&& request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
							PrintWriter printWriter = response.getWriter(); 
							printWriter.print("{sessionState:0}"); 
							printWriter.flush(); 
							printWriter.close(); }
					}
				}
				
		return true;
	}
}
